package com.example.demo.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.ApiSign;
import com.example.demo.common.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.TreeMap;

@Aspect
@Component
@Order(102)
@Slf4j
@RequiredArgsConstructor
public class SignAop {
    private final ApiSign apiSign;
    private final HttpServletResponse response;

    @Pointcut("@annotation(com.example.demo.annotate.CreateSign)")
    public void SignAop() { }

    @AfterReturning(pointcut = "SignAop()", returning = "result")
    public void afterReturning(Object result) {
        JSONObject js = ((Result) result).getData();
        TreeMap<String, Object> temp = new TreeMap<>();
        for (String key : js.keySet()) {
            temp.put(key, js.get(key).toString());
        }
        TreeMap<String, Object> map = apiSign.createSign(temp);

        /*((Result) result).put("nonce", map.get("nonce").toString());
        ((Result) result).put("timestamp", map.get("timestamp").toString());
        ((Result) result).put("sign", map.get("sign").toString());*/

        response.setHeader("nonce", map.get("nonce").toString());
        response.setHeader("timestamp", map.get("timestamp").toString());
        response.setHeader("sign", map.get("sign").toString());
    }

    @AfterThrowing(pointcut = "SignAop()", throwing = "t")
    public void afterThrowing(Throwable t) {
        log.error("errortext：{}" , t.getMessage());
    }
}
